package com.gxa.modules.pc.order.service.impl;

import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gxa.common.exception.ResultException;
import com.gxa.common.utils.DateUtils;
import com.gxa.common.utils.NoGenerateUtils;
import com.gxa.common.utils.Query;
import com.gxa.common.utils.TPage;
import com.gxa.modules.model.dto.BookInfoDTO;
import com.gxa.modules.model.dto.TimeAndNumDTO;
import com.gxa.modules.model.entity.book.BookRegister;
import com.gxa.modules.model.entity.book.Schedule;
import com.gxa.modules.model.vo.BookInfoVO;
import com.gxa.modules.model.vo.TimeAndNumVO;
import com.gxa.modules.pc.order.mapper.BookRegisterMapper;
import com.gxa.modules.pc.order.mapper.ScheduleMapper;
import com.gxa.modules.pc.order.service.BookRegisterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 预约挂号表 服务实现类
 * </p>
 *
 * @author zhuiyi
 * @since 2022-11-12 09:47:44
 */
@Slf4j
@Service
public class BookRegisterServiceImpl extends ServiceImpl<BookRegisterMapper, BookRegister> implements BookRegisterService {

    @Autowired
    private BookRegisterMapper bookRegisterMapper;

    @Autowired
    private ScheduleMapper scheduleMapper;

    @Override
    public TPage queryByPage(Map<String, Object> searchMap) {
        //其他的查询参数
        String name = (String) searchMap.get("name");
        String id = (String) searchMap.get("id");
        String status = (String) searchMap.get("status");
        String startTime = (String) searchMap.get("startTime");
        String endTime = (String) searchMap.get("endTime");
        String departmentId = (String) searchMap.get("departmentId");

        log.info("------name----{}--id---{}--", name, id);
        IPage<BookRegister> oldPage = this.page(new Query<BookRegister>().getPage(searchMap), new QueryWrapper<BookRegister>()
                .eq(!StringUtils.isBlank(id), "register_id", id)
                .eq(!StringUtils.isBlank(status),"status",status)
                .between(!StringUtils.isAnyBlank(startTime,endTime),"appoint_time",startTime,endTime)
                .and(!StringUtils.isBlank(name),qw->qw.likeRight("name",name).or().likeRight("doctor_name",name))
                .eq(!StringUtils.isBlank(departmentId),"department_id",departmentId)
        );
        return new TPage(oldPage);
    }

    @Override
    public BookInfoVO getBookInfo(Map<String, Object> paramMap) {
        //查询参数
        String departmentName = (String) paramMap.get("departmentName");
        String workDate = (String) paramMap.get("workDate");
        String parkId = (String) paramMap.get("parkId");
        String doctorName = (String) paramMap.get("doctorName");
        //其他参数
        String time = (String) paramMap.get("time");
        String username = (String) paramMap.get("username");
        String idCard = (String) paramMap.get("idCard");

        BookInfoDTO dto = bookRegisterMapper.getBookInfo(departmentName, workDate, doctorName, Integer.parseInt(parkId));

        BookInfoVO vo = new BookInfoVO();
        try {

        vo.setDoctorName(dto.getDoctorName());
        }catch (Exception e){
            throw new ResultException("参数错误，请换一下参数试试！");
        }
        vo.setTitle(dto.getTitle());
        vo.setHospitalName(dto.getHospitalName() + "--" + dto.getHospitalParkName());
        vo.setAddress(dto.getCity() + "--" + dto.getDistrict() + "--" + dto.getStreet());
        vo.setDeparAddress(dto.getDepAddress());
        vo.setWorkDate(dto.getWorkDate());
        String format = DateUtils.format(new Date(), "yyyy-MM-dd");
        vo.setBookDate(format);

        vo.setTime(time);
        vo.setFee(dto.getFee());
        //预约人信息
        vo.setName(username);
        vo.setIdCard(idCard);

        //成功生成后 存入 预约表 TODO
        BookRegister bookRegister = new BookRegister();
        bookRegister.setRegisterId(0L);
        bookRegister.setName(username);
        bookRegister.setCardNum(NoGenerateUtils.getRandomCode());
//        bookRegister.setPatientId("1"); //查询病人id
        bookRegister.setDepartment(vo.getDeparAddress());
        bookRegister.setType(0);
        bookRegister.setFee(vo.getFee());
        bookRegister.setStatus(0);
        bookRegister.setCureTime(DateUtils.stringToDate(vo.getWorkDate(), "yyyy-MM-dd"));
        bookRegister.setWaitCureTime(time); //9:30
        bookRegister.setAppointTime(new Date());
        bookRegister.setDoctorId(Long.parseLong(dto.getDoctorId()));
        bookRegister.setHospitalId(1L);
        bookRegister.setHospitalPartId(Long.parseLong(dto.getHoppitalParkId()));
//        bookRegister.setCancelTime(new Date());  //第一不用设置取消时间
        bookRegister.setCancelReason("");
        bookRegister.setRemark("我是备注");
        bookRegister.setIsDeleted(0);
        boolean save = this.save(bookRegister);
        if (!save) {
            throw new ResultException("生成的预约信息保存失败！！");
        }
        // 同时修改 排班表剩余的 可预约数量 和时间点的预约数 TODO
        String scheduleId = dto.getScheduleId();
        if (scheduleId == null) {
            throw new ResultException("没有该id");
        }
        //查询 排班
        Schedule schedule = this.scheduleMapper.selectById(scheduleId);
        if (schedule == null) {
            throw new ResultException("没有该排班");
        }
        //修改排班信息 剩余的总数量  以及 时间点的剩余数量
        Integer availableNumber = schedule.getAvailableNumber();
        if (availableNumber > 0) {
            schedule.setAvailableNumber(availableNumber - 1);
        }

        if ("9:00".equals(time)) {
            if (schedule.getAm9() > 0) {
                schedule.setAm9(schedule.getAm9() - 1);
            }
        } else if ("9:30".equals(time)) {
            if (schedule.getAm9H() > 0) {
                schedule.setAm9H(schedule.getAm9H() - 1);
            }
        } else if ("10:00".equals(time)) {
            if (schedule.getAm10() > 0) {
                schedule.setAm10(schedule.getAm10() - 1);
            }
        } else if ("10:30".equals(time)) {
            if (schedule.getAm10H() > 0) {
                schedule.setAm10H(schedule.getAm10H() - 1);
            }
        } else if ("11:00".equals(time)) {
            if (schedule.getAm11() > 0) {
                schedule.setAm11(schedule.getAm11() - 1);
            }
        } else if ("11:30".equals(time)) {
            if (schedule.getAm11H() > 0) {
                schedule.setAm11H(schedule.getAm11H() - 1);
            }
        } else if ("14:00".equals(time)) {
            if (schedule.getPm14() > 0) {
                schedule.setPm14(schedule.getPm14() - 1);
            }
        } else if ("14:30".equals(time)) {
            if (schedule.getPm14H() > 0) {
                schedule.setPm14H(schedule.getPm14H() - 1);
            }
        } else if ("15:00".equals(time)) {
            if (schedule.getPm15() > 0) {
                schedule.setPm15(schedule.getPm15() - 1);
            }
        } else if ("15:30".equals(time)) {
            if (schedule.getPm15H() > 0) {
                schedule.setPm15H(schedule.getPm15H() - 1);
            }
        } else if ("16:00".equals(time)) {
            if (schedule.getPm16() > 0) {
                schedule.setPm16(schedule.getPm16() - 1);
            }
        } else if ("16:30".equals(time)) {
            if (schedule.getPm16H() > 0) {
                schedule.setPm16H(schedule.getPm16H() - 1);
            }
        } else {
            throw new ResultException("更新时间点--的剩余预约数失败！");
        }

        this.scheduleMapper.updateById(schedule);
        return vo;
    }

    @Override
    public Map<String,Object> getTimeAndNum(HashMap<String, Object> params) {
        String doctorName = (String) params.get("doctorName");
        String workDate = (String) params.get("workDate");

        TimeAndNumDTO dto = this.bookRegisterMapper.getTimeAndNum(doctorName, workDate);
        Map<String,Object> map = new HashMap<>();
        List<TimeAndNumVO> am = new ArrayList<>();
        List<TimeAndNumVO> pm = new ArrayList<>();
        try {
            am.add(new TimeAndNumVO("9:00", dto.getAm9()));
            am.add(new TimeAndNumVO("9:30", dto.getAm9H()));
            am.add(new TimeAndNumVO("10:00", dto.getAm10()));
            am.add(new TimeAndNumVO("10:30", dto.getAm10H()));
            am.add(new TimeAndNumVO("11:00", dto.getAm11()));
            am.add(new TimeAndNumVO("11:30", dto.getAm11H()));

            pm.add(new TimeAndNumVO("14:00", dto.getPm14()));
            pm.add(new TimeAndNumVO("14:30", dto.getPm14H()));
            pm.add(new TimeAndNumVO("15:00", dto.getPm15()));
            pm.add(new TimeAndNumVO("14:30", dto.getPm15H()));
            pm.add(new TimeAndNumVO("16:00", dto.getPm16()));
            pm.add(new TimeAndNumVO("16:30", dto.getPm16H()));
        }catch (NullPointerException e){
            throw new ResultException("请换个医生或 时间");
        }
        map.put("am",am);
        map.put("pm",pm);

        return map;
    }

    @Override
    public Map<String, Object> getWeekDays() {
        Map<String,Object> map = new HashMap<>();

        //list<Stirng>
        List<String> stringWeekDays = DateUtils.getStringWeekDays(0);
        //today.
        String stringToday = DateUtils.getStringToday();
        map.put("today",stringToday);
        map.put("weekDays",stringWeekDays);
        return map;
    }


}
